package org.neu.ccs.secureim;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Key;
import java.security.PublicKey;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.DHParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class ClientListenerThread implements Runnable{

	ChatClient client;
	
	static final int CONNECT = 7;
	static final int MESSAGE = 8;
	
	ServerSocket servSock;
	
	public ClientListenerThread(ChatClient client)
	{
		this.client = client;
	}
	
	public int initSocket() throws IOException
	{
		servSock = new ServerSocket(0);
		return servSock.getLocalPort();
	}
	
	@Override
	public void run() {
		
		while(true)
		{
			try
			{
				Socket sock = servSock.accept();
				if( !sock.isConnected() )
					continue;
				
				DataInputStream sin = new DataInputStream(sock.getInputStream());
				
				int command = sin.read();

				if( command == CONNECT )
				{
					System.out.println("Incoming connection...");
					int length = NetworkHelper.ReadInt(sin);
					
					if( length > 1500 )
					{
						System.out.println("Unexpected response");
						continue;
					}
					
					byte[] userMessage = new byte[length];
					sin.readFully(userMessage);
					
					String userName = new String(CryptoHelper.UnpackRSA(client.clientPair.getPrivate(), userMessage));
					System.out.println("Locating " + userName + "...");
					UserInfo info = client.locate(userName);
					
					length = NetworkHelper.ReadInt(sin);
					
					if( length > 1500 )
					{
						System.out.println("Unexpected response");
						continue;
					}
					
					byte[] message1 = new byte[length];
					sin.readFully(message1);
					
					if( !CryptoHelper.VerifyRSA(info.getPubKey(), message1) )
					{
						System.out.println("Incoming connection verification failed.");
					}
					
					ByteArrayInputStream in = new ByteArrayInputStream(Arrays.copyOfRange(message1, 256, message1.length));
					ObjectInputStream deserializer = new ObjectInputStream(in);
					
					BigInteger p = (BigInteger)deserializer.readObject();
					BigInteger g = (BigInteger)deserializer.readObject();
					int l = deserializer.readInt();
					DHParameterSpec spec = new DHParameterSpec(p, g, l);
					PublicKey pubkey = (PublicKey)deserializer.readObject();
					
					DHValues vals = new DHValues(spec);
					Key symKey = vals.doFinal(pubkey, "AES");
					
					if( client.sharedKeys.containsKey(userName) )
						client.sharedKeys.remove(userName);
					client.sharedKeys.put(userName, symKey);
					
					Mac mac = Mac.getInstance("HmacSHA1");
					mac.init(symKey);
					mac.update(userName.getBytes());
					byte[] hash = mac.doFinal();
					
					client.userHashes.put(Base64.encodeBase64String(hash), userName);
					
					if( client.userLocs.containsKey(userName))
						client.userLocs.remove(userName);
					client.userLocs.put(userName, info);
					
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					ObjectOutputStream serializer = new ObjectOutputStream(out);
					serializer.writeObject(vals.getPublicKey());
					serializer.flush();
					
					byte[] signed2 = CryptoHelper.SignRSA(client.clientPair.getPrivate(), out.toByteArray());
					
					OutputStream sout = sock.getOutputStream();
					NetworkHelper.WriteInt(sout,signed2.length);
					sout.write(signed2);
				
				}else if (command == MESSAGE){
					
					int length = NetworkHelper.ReadInt(sin);
					
					if( length > 1500 )
					{
						System.out.println("Unexpected response");
						continue;
					}
					
					byte[] userHash = new byte[length];
					sin.readFully(userHash);
					
					if( !client.userHashes.containsKey(Base64.encodeBase64String(userHash)) )
					{
						System.out.println("Unauthenticated user attempted to connect");
						return;
					}
					
					String userName = client.userHashes.get(Base64.encodeBase64String(userHash));
					Key symKey = client.sharedKeys.get(userName);
					
					length = NetworkHelper.ReadInt(sin);
					
					if( length > 1500 )
					{
						System.out.println("Unexpected response");
						return;
					}
					
					byte[] encmessage = new byte[length];
					sin.readFully(encmessage);
					
					length = NetworkHelper.ReadInt(sin);
					
					if( length > 1500 )
					{
						System.out.println("Unexpected response");
						return;
					}
					
					byte[] hmacReceived = new byte[length];
					sin.readFully(hmacReceived);
					
					// DECRYPT MESSAGE WITH SHARED SESSION KEY
					Cipher cipher = Cipher.getInstance("AES");
					cipher.init(Cipher.DECRYPT_MODE, symKey);
		            byte[] decrypted = cipher.doFinal(encmessage);
		            
		            // Generate HMAC(KEY, MESSAGE) and test against received value
					Mac m = Mac.getInstance("HmacSHA1");
					m.init(symKey);
					m.update(decrypted);
					byte[] hmacCalculated = m.doFinal();
					
		            if (Arrays.equals(hmacCalculated, hmacReceived)){
		            	System.out.println(userName + ": " + new String(decrypted));
		            }else {
		            	System.out.println("HMAC verification failed from " + userName);
		            }
		            
					
				}
				
				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}
